package category

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/iancoleman/strcase"
	"go.uber.org/zap"
	"goods_bff/controller"
	"goods_bff/goods_proto"
	"goods_bff/pkg"
	"net/http"
)

func CategoryList(c *gin.Context) {
	comment := pkg.Comment()
	categoryList, err := comment.GetAllCategoryList(context.Background(), &goods_proto.Empty{})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}

	category := make([]interface{}, 0)

	err = json.Unmarshal([]byte(categoryList.JsonData), &category)
	if err != nil {
		zap.S().Errorw("[List] 查询 【分类列表】失败： ", err.Error())
	}

	snakeCaseCategory := convertMapKeysToSnakeCase(category)

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": snakeCaseCategory,
	})
}

func convertMapKeysToSnakeCase(data interface{}) interface{} {
	switch val := data.(type) {
	case map[string]interface{}:
		newMap := make(map[string]interface{})
		for k, v := range val {
			newMap[strcase.ToSnake(k)] = convertMapKeysToSnakeCase(v)
		}
		return newMap
	case []interface{}:
		for i, v := range val {
			val[i] = convertMapKeysToSnakeCase(v)
		}
		return val
	default:
		return data
	}
}
